package info.demo.filter.tag;


import info.demo.filter.Crypto;
import info.demo.filter.CryptoFilter;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;


public class EncryptUrlTag extends SimpleTagSupport {

    private int scope;
    private String var;
    private String context;
    private String value;

    public EncryptUrlTag() {
        this.scope = PageContext.PAGE_SCOPE;
        this.var = null;
        this.context = null;
        this.value = null;
    }

    public void doTag() throws JspException, IOException {
        PageContext pageContext = (PageContext) getJspContext();
        String baseUrl = TagUtils.resolveUrl(value, context, pageContext);
        String cryptoUrlParamName = pageContext.getServletContext().getInitParameter(Crypto.INIT_PARAMETER);
        if (cryptoUrlParamName == null)
            cryptoUrlParamName = Crypto.URL_PARAM_NAME;
        String url = pageContext.getServletContext().getAttribute(CryptoFilter.FILTER_ENABLED) != null 
                ? Crypto.encryptUrl(cryptoUrlParamName, baseUrl)
                : baseUrl;
        // Se a URL é relativa, reescreva-a
        if (!TagUtils.isAbsoluteUrl(url)) {
            HttpServletResponse response = ((HttpServletResponse) pageContext.getResponse());
            url = response.encodeURL(url);
        }
        // Armazena ou imprime a URL
        if (var != null)
            pageContext.setAttribute(var, url, scope);
        else {
            try {
                pageContext.getOut().print(url);
            } catch (java.io.IOException ex) {
                throw new JspTagException(ex.toString(), ex);
            }
        }
    }

    public void setContext(String context) {
        this.context = context;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public void setVar(String var) {
        this.var = var;
    }

    public void setScope(String scope) {
        this.scope = TagUtils.getScope(scope);
    }

}
